package com.dwin.h5.app.services.mqtt;

import android.util.Log;

import com.dwin.h5.app.utils.HexTool;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.greenrobot.eventbus.EventBus;

/**
 * 使用EventBus分发事件
 *
 * @author LichFaker on 16/3/25.
 */
public class MqttCallbackBus implements MqttCallback {
    private static final String TAG = "MqttManager";

    @Override
    public void connectionLost(Throwable cause) {
//        Logger.e(cause.getMessage());
        Log.d(TAG, "connectionLost: " + cause.getMessage());
        Log.d(TAG, "connectionLost: " + cause.getCause());
        Log.d(TAG, "connectionLost: " + cause.getLocalizedMessage());
        Log.d(TAG, "connectionLost: " + cause);
        // 通过eventBus发送消息给Activity，尝试重连mqtt服务器
        EventBus.getDefault().post(new DataSynEvent("connectionLost:"));
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) {
        Log.d(TAG, "topic:" + topic);
        if (topic.contains("json")) {
            MqttMessageWithTopic messageWithTopic = new MqttMessageWithTopic(topic, message);
            EventBus.getDefault().post(messageWithTopic);
        } else if (topic.contains("image")) {
            String hexMsg = HexTool.bytesToHex(message.getPayload());
            EventBus.getDefault().post(hexMsg);
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
    }

}
